/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.purpose.service.impl;

import com.google.common.base.Splitter;
import com.koron.common.bean.DepartmentTreeBean;
import com.koron.common.bean.DeptBean;
import com.koron.common.bean.StaffBean;
import com.koron.common.domain.DataBean;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.common.web.Util;
import com.koron.purpose.bean.JobsStaffBean;
import com.koron.purpose.bean.ResponsibilitiesLibBean;
import com.koron.purpose.domain.*;
import com.koron.purpose.mapper.*;
import com.koron.purpose.service.api.JobsStaffService;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.swan.bean.MessageBean;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class JobsStaffServiceImpl implements JobsStaffService {
    private final static Logger logger= LoggerFactory.getLogger(JobsStaffServiceImpl.class);

    @Autowired
    private Util util;


    @SuppressWarnings({"rawtypes", "deprecation"})
    @Override
    public MessageBean<?> insert(JobsStaffBean bean, StaffBean user) {
        MessageBean<?> msg = MessageBean.create(0, "SUCCESS", void.class);
        Map checkMap = addCheck(bean);
        int code = (int) checkMap.get("code");
        String description = (String) checkMap.get("description");
        if (code != 0) {
            msg.setCode(code);
            msg.setDescription(description);
            return msg;
        }
        SessionFactory factory = new SessionFactory();
        try {
            String staffCode = bean.getStaffCode();
            JobsStaffMapper mapper = factory.getMapper(JobsStaffMapper.class);
            Integer count = mapper.addVerification(staffCode);
            if (count > 0) {
                factory.close(false);
                msg.setCode(35002);
                msg.setDescription("该人员已设定岗位");
                return msg;
            }
            bean.setAddTime(new Date());
            bean.setAddUser(user.getCode());
            bean.setAddUserName(user.getName());
            bean.setUpdateTime(new Date());
            bean.setUpdateUser(user.getCode());
            bean.setUpdateUserName(user.getName());
            bean.setId(staffCode);
            //定人定岗
            List<JobsStaffTask> taskList = bean.getTaskList();
            for (JobsStaffTask task : taskList) {
                task.setId(DefaultIdGenerator.getInstance().generateLongId());
                task.setJobsStaffId(bean.getId());
            }
            //证照要求
            List<JobsStaffCertificate> certificateList = bean.getCertificateList();
            for (JobsStaffCertificate certificate : certificateList) {
                certificate.setId(DefaultIdGenerator.getInstance().generateLongId());
                certificate.setJobsStaffId(bean.getId());
            }
            //培训要求
            List<JobsStaffTraining> trainingList = bean.getTrainingList();
            for (JobsStaffTraining training : trainingList) {
                training.setId(DefaultIdGenerator.getInstance().generateLongId());
                training.setJobsStaffId(bean.getId());
            }
            //危害因素
            List<JobsStaffHazard> hazardList = bean.getHazardList();
            for (JobsStaffHazard hazard : hazardList) {
                hazard.setId(DefaultIdGenerator.getInstance().generateLongId());
                hazard.setJobsStaffId(bean.getId());
            }
            if (!taskList.isEmpty()) {
                factory.getMapper(JobsStaffTaskMapper.class).batchInsert(taskList);
            }
            if (!certificateList.isEmpty()) {
                factory.getMapper(JobsStaffCertificateMapper.class).batchInsert(certificateList);
            }
            if (!trainingList.isEmpty()) {
                factory.getMapper(JobsStaffTrainingMapper.class).batchInsert(trainingList);
            }
            if (!hazardList.isEmpty()) {
                factory.getMapper(JobsStaffHazardMapper.class).batchInsert(hazardList);
            }
            // 新增 人员岗位-职责项
            batchInsertRL(bean.getId(), bean.getResponsibilitiesLibIds(), factory);
            mapper.insert(bean);
            factory.close();
        } catch (Exception e) {
            factory.close(false);
            msg.setCode(35001);
            msg.setDescription("数据库连接异常");
            return msg;
        }finally {
            if (null != factory) {
                factory.close();
            }
        }
        return msg;
    }

    @SuppressWarnings({"rawtypes", "deprecation"})
    @Override
    public MessageBean<?> update(JobsStaffBean bean, StaffBean user) {
        MessageBean<?> msg = MessageBean.create(0, "SUCCESS", void.class);
        Map checkMap = addCheck(bean);
        int code = (int) checkMap.get("code");
        String description = (String) checkMap.get("description");
        if (code != 0) {
            msg.setCode(code);
            msg.setDescription(description);
            return msg;
        }
        if (StringUtils.isEmpty(bean.getId())) {
            msg.setCode(35002);
            msg.setDescription("参数校验异常");
            return msg;
        }
        if (queryById(bean.getId()) == null) {
            msg.setCode(35002);
            msg.setDescription("参数校验异常");
            return msg;
        }
        SessionFactory factory = new SessionFactory();
        try {
            JobsStaffMapper mapper = factory.getMapper(JobsStaffMapper.class);
            bean.setUpdateTime(new Date());
            bean.setUpdateUser(user.getCode());
            bean.setUpdateUserName(user.getName());
            //定人定岗
            List<JobsStaffTask> taskList = bean.getTaskList();
            for (JobsStaffTask task : taskList) {
                task.setId(DefaultIdGenerator.getInstance().generateLongId());
                task.setJobsStaffId(bean.getId());
            }
            //证照要求
            List<JobsStaffCertificate> certificateList = bean.getCertificateList();
            for (JobsStaffCertificate certificate : certificateList) {
                certificate.setId(DefaultIdGenerator.getInstance().generateLongId());
                certificate.setJobsStaffId(bean.getId());
            }
            //培训要求
            List<JobsStaffTraining> trainingList = bean.getTrainingList();
            for (JobsStaffTraining training : trainingList) {
                training.setId(DefaultIdGenerator.getInstance().generateLongId());
                training.setJobsStaffId(bean.getId());
            }
            //危害因素
            List<JobsStaffHazard> hazardList = bean.getHazardList();
            for (JobsStaffHazard hazard : hazardList) {
                hazard.setId(DefaultIdGenerator.getInstance().generateLongId());
                hazard.setJobsStaffId(bean.getId());
            }
            //删除子表数据
            factory.getMapper(JobsStaffTaskMapper.class).delete(bean.getId());
            factory.getMapper(JobsStaffCertificateMapper.class).delete(bean.getId());
            factory.getMapper(JobsStaffTrainingMapper.class).delete(bean.getId());
            factory.getMapper(JobsStaffHazardMapper.class).delete(bean.getId());

            if (!taskList.isEmpty()) {
                factory.getMapper(JobsStaffTaskMapper.class).batchInsert(taskList);
            }
            if (!certificateList.isEmpty()) {
                factory.getMapper(JobsStaffCertificateMapper.class).batchInsert(certificateList);
            }
            if (!trainingList.isEmpty()) {
                factory.getMapper(JobsStaffTrainingMapper.class).batchInsert(trainingList);
            }
            if (!hazardList.isEmpty()) {
                factory.getMapper(JobsStaffHazardMapper.class).batchInsert(hazardList);
            }
            // 根据 岗位职责id 删除 人员岗位-职责项
            factory.getMapper(JobsStaffMapper.class).deleteRLByStaffId(bean.getId());
            // 新增 人员岗位-职责项
            batchInsertRL(bean.getId(), bean.getResponsibilitiesLibIds(), factory);
            mapper.update(bean);
            factory.close();
        } catch (Exception e) {
            factory.close(false);
            msg.setCode(35001);
            msg.setDescription("数据库连接异常");
            return msg;
        }finally {
            if (null != factory) {
                factory.close();
            }
        }
        return msg;
    }

    @SuppressWarnings("deprecation")
    @Override
    public MessageBean<?> delete(String id) {
        MessageBean<?> msg = MessageBean.create(0, "success", void.class);
        JobsStaffBean bean = queryById(id);
        if (bean == null) {
            msg.setCode(35002);
            msg.setDescription("参数校验异常");
            return msg;
        }
        SessionFactory factory = new SessionFactory();
        try {
            factory.getMapper(JobsStaffMapper.class).delete(id);
            factory.getMapper(JobsStaffTaskMapper.class).delete(id);
            factory.getMapper(JobsStaffCertificateMapper.class).delete(id);
            factory.getMapper(JobsStaffTrainingMapper.class).delete(id);
            factory.getMapper(JobsStaffHazardMapper.class).delete(id);
            factory.close();
        } catch (Exception e) {
            factory.close(false);
            msg.setCode(35001);
            msg.setDescription("数据库连接异常");
        }
        return msg;
    }

    @Override
    public MessageBean<?> details(String id) {
        MessageBean<JobsStaffBean> msg = MessageBean.create(0, "success", JobsStaffBean.class);
        JobsStaffBean bean = queryById(id);
        msg.setData(bean);
        return msg;
    }

    @Override
    public MessageBean<?> staffTaskList(String name, String jobsName, String taskTypeId, String cycleId, Integer page, Integer pageSize) {
        MessageBean<DataBean> msg = MessageBean.create(0, "SUCCESS", DataBean.class);
        Integer totalPage = null;
        Integer totalNumber = null;
        Integer start = null;
        Integer end = null;
        if (null != page && pageSize != null) {
            if (page > 0 && pageSize > 0) {
            } else {
                //第一页 10条数据
                page = 1;
                pageSize = 10;
            }
            start = (page <= 1) ? 0 : (page - 1) * pageSize;
            end = pageSize;
        }
        if (StringUtils.isEmpty(name)) {
            name = "%%";
        } else {
            name = "%" + name + "%";
        }
        if (StringUtils.isEmpty(jobsName)) {
            jobsName = "%%";
        } else {
            jobsName = "%" + jobsName + "%";
        }
        try (SessionFactory factory = new SessionFactory()) {
            totalNumber = factory.getMapper(JobsStaffTaskMapper.class).queryStaffTasksCount(name, jobsName, taskTypeId, cycleId);
            if (start != null && end != null) {
                totalPage = (totalNumber + pageSize - 1) / pageSize;
            } else {
                totalPage = 1;
                page = totalPage;
                pageSize = totalNumber;
            }
            List<StaffWorks> list = factory.getMapper(JobsStaffTaskMapper.class).queryStaffTasks(name, jobsName, taskTypeId, cycleId, start, end);

            Map<String, String> corpMap = new HashMap<>();
            Map<String, String> deptMap = new HashMap<>();

            for (StaffWorks task : list) {
                String staffCode = task.getStaffCode();
                String corpCode = corpMap.get(staffCode);
                if (corpCode == null) {
                    MessageBean<?> temp = util.corp(staffCode);
                    if (temp.getCode() == 0 && null != temp.getData()) {
                        DepartmentTreeBean corp = (DepartmentTreeBean) temp.getData();
                        task.setCorpCode(corp.getDepartmentCode());
                        task.setCorpName(corp.getName());
                        corpMap.put(staffCode, corp.getDepartmentCode());
                        corpMap.put(staffCode + "#name", corp.getName());
                    }
                } else {
                    task.setCorpCode(corpCode);
                    task.setCorpName(corpMap.get(staffCode + "#name"));
                }
                String deptCode = deptMap.get(staffCode);
                if (deptCode == null) {
                    MessageBean<?> temp = util.dept(staffCode);
                    if (temp.getCode() == 0 && null != temp.getData()) {
                        List<DeptBean> deptList = (List<DeptBean>) temp.getData();
                        if (!deptList.isEmpty()) {
                            DeptBean dept = deptList.get(0);
                            if (dept != null) {
                                task.setDeptCode(dept.getCode());
                                task.setDeptName(dept.getName());
                                deptMap.put(staffCode, dept.getCode());
                                deptMap.put(staffCode + "#name", dept.getName());
                            }
                        }
                    }
                } else {
                    task.setDeptCode(deptCode);
                    task.setDeptName(deptMap.get(staffCode + "#name"));
                }

            }

            DataBean data = new DataBean();
            data.setList(list);
            data.setPageNo(page);
            data.setPageSize(pageSize);
            data.setTotalNumber(totalNumber);
            data.setTotalPage(totalPage);
            msg.setData(data);
        } catch (Exception e) {
            msg.setCode(35001);
            msg.setDescription("数据库连接异常");
        }
        return msg;
    }

    @SuppressWarnings({"rawtypes", "deprecation", "unchecked"})
    @Override
    public MessageBean<?> list(String deptCode,String name, Integer page, Integer pageSize) {
        MessageBean<DataBean> msg = MessageBean.create(0, "SUCCESS", DataBean.class);
        if (StringUtils.isEmpty(deptCode)) {
            return msg;
        }
        Integer totalPage = null;
        Integer totalNumber = null;
        Integer start = null;
        Integer end = null;
        if (null != page && pageSize != null) {
            if (page > 0 && pageSize > 0) {
            } else {
                //第一页 10条数据
                page = 1;
                pageSize = 10;
            }
            start = (page <= 1) ? 0 : (page - 1) * pageSize;
            end = page * pageSize;
        }
        try (SessionFactory factory = new SessionFactory()) {
            //获取部门人员
            MessageBean staffMsg = util.depstaff(deptCode);
            if (staffMsg.getCode() != 0) {
                return staffMsg;
            }
            if (staffMsg.getData() == null) {
                return msg;
            }
            // 拿到部门下的所有人员
            List<StaffBean> allStaffList = (List<StaffBean>) staffMsg.getData();
            if(StringUtils.isNotBlank(name)){
                allStaffList = allStaffList.stream().filter(staffBean -> staffBean.getName().contains(name)).collect(Collectors.toList());
            }
            // 过滤掉停用的人员
            List<StaffBean> staffList = allStaffList.stream().filter(staffBean -> staffBean.getStatus() == 0).collect(Collectors.toList());
            if (staffList.isEmpty()) {
                return msg;
            }
            totalNumber = staffList.size();  //部门人员总数
            if (start != null && end != null) { //需要分页
                totalPage = (totalNumber + pageSize - 1) / pageSize;
                if (end > totalNumber) {
                    end = totalNumber;
                }
                staffList = staffList.subList(start, end);
            } else {
                totalPage = 1;
                page = totalPage;
                pageSize = totalNumber;
            }
            List<String> codeList = staffList.stream().map(StaffBean::getCode).collect(Collectors.toList());
            if (codeList.isEmpty()) {
                return msg;
            }
            JobsStaffMapper mapper = factory.getMapper(JobsStaffMapper.class);
            List<JobsStaffBean> list = mapper.queryByCodeList(codeList);
            list.stream().forEach(jobsStaffBean -> {
                // 根据 岗位职责id 查询 人员岗位-职责
                List<ResponsibilitiesLibBean> responsibilitiesLibBeans = factory.getMapper(JobsStaffMapper.class).getResponsibilitiesLibs(jobsStaffBean.getId());
                jobsStaffBean.setResponsibilitieList(responsibilitiesLibBeans);
                StringBuffer sb = new StringBuffer();
                if (responsibilitiesLibBeans != null && responsibilitiesLibBeans.size() > 0) {
                    for (int i = 0, size = responsibilitiesLibBeans.size(); i < size; i++) {
                        sb.append((i + 1) + ".");
                        if (i == size - 1) {
                            sb.append(responsibilitiesLibBeans.get(i).getItem());
                        } else {
                            sb.append(responsibilitiesLibBeans.get(i).getItem() + "\n");
                        }
                    }
                }
                jobsStaffBean.setNote(sb.toString());
            });
            Map<String, JobsStaffBean> map = list.stream().collect(Collectors.toMap(JobsStaffBean::getId, Function.identity(), (key1, key2) -> key2));
            List<JobsStaffBean> ret = new ArrayList<>();
            for (StaffBean user : staffList) {
                if (map.keySet().contains(user.getCode())) {
                    ret.add(map.get(user.getCode()));
                } else {
                    JobsStaffBean bean = new JobsStaffBean();
                    bean.setStaffCode(user.getCode());
                    bean.setStaffName(user.getName());
                    ret.add(bean);
                }
            }
            DataBean data = new DataBean();
            data.setPageNo(page);
            data.setPageSize(pageSize);
            data.setTotalNumber(totalNumber);
            data.setTotalPage(totalPage);
            data.setList(ret);
            msg.setData(data);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(35001);
            msg.setDescription("数据库连接异常");
        }
        return msg;
    }

    @SuppressWarnings("deprecation")
    public JobsStaffBean queryById(String id) {
        JobsStaffBean bean;
        try (SessionFactory factory = new SessionFactory();) {
            bean = factory.getMapper(JobsStaffMapper.class).queryById(id);
            if (bean == null) {
                return bean;
            }
            bean.setTaskList(factory.getMapper(JobsStaffTaskMapper.class).queryByTid(id));
            bean.setCertificateList(factory.getMapper(JobsStaffCertificateMapper.class).queryByTid(id));
            bean.setTrainingList(factory.getMapper(JobsStaffTrainingMapper.class).queryByTid(id));
            bean.setHazardList(factory.getMapper(JobsStaffHazardMapper.class).queryByTid(id));
            // 根据 岗位职责id 查询 人员岗位-职责
            bean.setResponsibilitieList(factory.getMapper(JobsStaffMapper.class).getResponsibilitiesLibs(id));
        }
        return bean;
    }

    @SuppressWarnings({"rawtypes", "unchecked"})
    private Map addCheck(JobsStaffBean bean) {
        Map map = new HashMap();
        if (bean == null) {
            map.put("code", 35002);
            map.put("description", "请填写人员信息");
            return map;
        }
        if (StringUtils.isEmpty(bean.getStaffCode())) {
            map.put("code", 35002);
            map.put("description", "请填写人员信息");
            return map;
        }
        if (StringUtils.isEmpty(bean.getDeptCode())) {
            map.put("code", 35002);
            map.put("description", "请填写部门信息");
            return map;
        }
        map.put("code", 0);
        map.put("description", "校验成功");
        return map;
    }

    /**
     * @param beanId
     * @param responsibilitiesLibIds
     * @param factory
     */
    private void batchInsertRL(String beanId, String responsibilitiesLibIds, SessionFactory factory) throws Exception {
        try {
            if (!StringUtils.isEmpty(responsibilitiesLibIds)) {
                List<String> ids = Splitter.on(",").omitEmptyStrings().trimResults().splitToList(responsibilitiesLibIds);
                List<Map> rls = new LinkedList<>();
                Map map;
                for (String id : ids) {
                    map = new HashMap();
                    map.put("jobsStaffId", beanId);
                    map.put("responsibilitiesLibId", id);
                    rls.add(map);
                }
                rls = rls.stream().distinct().collect(Collectors.toList());
                factory.getMapper(JobsStaffMapper.class).batchInsertRL(rls);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            throw new Exception(e.getMessage());
        }
    }
}
